const Router = require('koa-router')
const router = new Router()
const multiparty = require('multiparty')
const path = require('path')
const fs = require('fs')
const { resolve } = require('path')

let UPLOAD_DIR = path.resolve(__dirname, '..', "target")
let NEW_UPLOAD_DIR = null

router.post('/file', ctx => {
  let { filename, filehash } = ctx.request.body
  NEW_UPLOAD_DIR = path.resolve(UPLOAD_DIR, filehash)
  if (Math.random() < 0.5) {
    ctx.status = 500
    return ctx.body = {
      desc: '上传失败',
      status: false
    }
  } else {
    // 创建文件夹
    fs.stat(NEW_UPLOAD_DIR, (err, stats) => {
      if (!stats) {
        fs.mkdir(NEW_UPLOAD_DIR, err => {
          writeFile(ctx)
        })
      }
      writeFile(ctx)
    })
    ctx.status = 200
    return ctx.body = {
      status: true
    }
  }

})

const writeFile = (ctx) => {
  // 拼接hash以及文件大小
  let { filename, hash } = ctx.request.body
  const file = ctx.request.files.chunk
  const size = '-' + file.size
  const newHash = hash + size
  const reader = fs.createReadStream(file.path)
  let filePath = path.resolve(NEW_UPLOAD_DIR, newHash)
  const writerStream = fs.createWriteStream(filePath)
  reader.pipe(writerStream)
}

const pipeStream = (path, writerStream) => {
  new Promise(resolve => {
    const readStream = fs.createReadStream(path)
    readStream.on('end', () => {
      fs.unlinkSync(path)
      resolve()
    })
    readStream.pipe(writerStream)
  })
}

// 提取后缀名
const extractExt = filename => filename.slice(filename.lastIndexOf('.'), filename.length)

router.post('/merge', async ctx => {
  const { filehash, filename } = ctx.request.body
  const chunksPath = fs.readdirSync(NEW_UPLOAD_DIR)

  chunksPath.sort((a, b) => a.split("-")[1] - b.split("-")[1])

  const filepath = path.resolve(NEW_UPLOAD_DIR, filename)

  await Promise.all(
    chunksPath.map((chunkPath, index) => {
      const size = Number(chunkPath.split('-')[2])
      pipeStream(
        path.resolve(NEW_UPLOAD_DIR, chunkPath),
        fs.createWriteStream(filepath, {
          start: index * size,
          end: (index + 1) * size
        })
      )
    })
  )
  ctx.status = 200
  ctx.body = '上传成功'
})

const createUploadedList = filehash => {
  const filepath = path.resolve(UPLOAD_DIR, filehash)
  return fs.existsSync(filepath)
    ? fs.readdirSync(filepath).map(v => v.slice(0, v.lastIndexOf('-')))
    : []
}

router.post('/verify', ctx => {
  let { filename, filehash } = ctx.request.body
  const filepath = path.resolve(UPLOAD_DIR, filehash, filename)
  if (fs.existsSync(filepath)) {
    ctx.body = {
      hasFile: true
    }
  } else {
    const uploadedList = createUploadedList(filehash)
    console.log(uploadedList)
    ctx.body = {
      hasFile: false,
      uploadedList: uploadedList
    }
  }
  ctx.status = 200
  return
})


module.exports = router